from fastapi import Depends
from sqlalchemy import and_, desc

from forward.api.h5.orm.merchant import MerchantORM
from forward.api.h5.schemas.merchant import MerchantAddInSchema, MerchantListInSchema
from forward.extend.pydantic.result_api import ResultAPI
from forward.model.tables.merchant import MerchantModel


class MerchantService:
    def __init__(self, merchant_orm: MerchantORM = Depends()):
        self.merchant_orm = merchant_orm

    async def lists(self, list_in: MerchantListInSchema):
        where = []
        if list_in.name:
            where.append(MerchantModel.name.like(f"%{list_in.name}%"))
        order_by = [MerchantModel.created_time.desc()]
        pagination = await self.merchant_orm.paginate(
            page_num=list_in.page_num,
            page_size=list_in.page_size,
            where=where,
            order_by=order_by,
        )
        return ResultAPI(data={"lists": pagination.lists, "total": pagination.total})

    async def detail(self, merchant_id: int):
        pass

    async def add(self, merchant_in: MerchantAddInSchema):
        await self.merchant_orm.create(merchant_in.model_dump())
        return ResultAPI(data={})
